package com.ourteam.workspace.api;

import java.io.File;

import org.apache.commons.lang.ArrayUtils;

import com.ourteam.frame.web.AbstractTreeNodeBuilder;
import com.ourteam.workspace.dao.WorkspaceDAOQueryBean;
import com.ourteam.workspace.dao.WorkspaceResourceDAOQueryBean;
import com.ourteam.workspace.domain.WorkspaceBean;
import com.ourteam.workspace.service.IWorkspaceService;
import com.ourteam.workspace.service.WorkspaceServiceFactory;

public class WorkspaceNodeBuilder extends AbstractTreeNodeBuilder<Object, WorkspaceBean>
		implements IWorkspaceResourceNodeBuilder {

	private static final IWorkspaceService workspaceService = WorkspaceServiceFactory.getWorkspaceService();

	private long workspaceId;

	private File workspaceRootDir;

	public void setWorkspaceRootDir(File workspaceRootDir) {
		this.workspaceRootDir = workspaceRootDir;
	}

	public long getWorkspaceId() {
		return workspaceId;
	}

	public void setWorkspaceId(long workspaceId) {
		this.workspaceId = workspaceId;
	}

	@Override
	public WorkspaceBean[] getTreeNodeObjects(Object parentObject) throws Exception {

		WorkspaceDAOQueryBean queryBean = new WorkspaceDAOQueryBean();
		
		queryBean.createCriteria().andIdEqualTo(workspaceId);

		return workspaceService.queryWorkspaces(queryBean);

	}

	@Override
	public Object getNodeId(WorkspaceBean childObject) throws Exception {
		return childObject.getId();
	}

	@Override
	public boolean isLeaf(WorkspaceBean childObject) throws Exception {
		return false;
	}

	@Override
	public int getChildCount(WorkspaceBean childObject) throws Exception {

		WorkspaceResourceDAOQueryBean queryBean = new WorkspaceResourceDAOQueryBean();

		queryBean.createCriteria().andWorkspaceIdEqualTo(childObject.getId());

		int resourceCount = workspaceService.queryWorkspaceResourceCount(queryBean);

		File workspacePathFile = new File(workspaceRootDir, childObject.getWorkspacePath());

		int fileCount = 0;

		if (workspacePathFile.exists()) {

			fileCount = ArrayUtils.getLength(workspacePathFile.list());
		}

		return resourceCount + fileCount;
	}

	@Override
	public String getNodeDefineId(WorkspaceBean childObject) throws Exception {
		return "workspaceNode";
	}

	@Override
	public Object converToParentObject(Object parent) throws Exception {
		return null;
	}

}
